import dayjs from "dayjs";
import axios from "axios";

// 使用响应式数据，方便其他组件引用
let nameList = "".split(",");
let roomIdList = "".split(",");
let dataReady = false;
let dataUpdatedCallback = null;

// 节假日数据
let holidayMap = new Map(); // 用于快速查询日期是否为节假日

// 存储认证token
let authToken = null;
let orderId = null;
let orderNo = null;

window.addEventListener('message', (event) => {
  if (event.data.type === 'setToken') {
    const token = event.data.token;
    const orderId = event.data.id;
    const orderNo = event.data.orderNo;
    setAuthToken(token, orderId, orderNo);
    fetchRoomList(token);
  }
});

// 设置认证token
export function setAuthToken(token, id, no) {
  if (token) {
    authToken = token;
    orderId = id;
    orderNo = no
    localStorage.setItem('token', token);
    localStorage.setItem('orderId', id);
    localStorage.setItem('orderNo', no);
    return true;
  }
  return false;
}

// 获取认证token
export function getAuthToken() {
  if (!authToken) {
    authToken = localStorage.getItem('token') || sessionStorage.getItem('token');
  }
  return authToken;
}

// 导出获取最新nameList的函数
export function getNameList() {
  return nameList;
}

// 导出获取最新roomIdList的函数
export function getRoomIdList() {
  return roomIdList;
}

// 注册数据更新回调
export function onDataUpdated(callback) {
  dataUpdatedCallback = callback;
}

// 导出数据是否准备好的状态
export function isDataReady() {
  return dataReady;
}

// 获取节假日数据
export async function fetchHolidayData(year) {
  try {
    const token = getAuthToken();
    if (!token) {
      return new Map();
    }
    
    const response = await axios.get('http://10.77.162.117:18092/admin/tjsScheduling/calendar/list', {
      params: { year },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.data && response.data.code === 200 && response.data.data) {
      holidayMap.clear();
      
      response.data.data.forEach(month => {
        if (month.days && Array.isArray(month.days)) {
          month.days.forEach(day => {
            holidayMap.set(day.day, {
              type: day.type,
              remark: day.remark
            });
          });
        }
      });
      
      if (window.$bus) {
        window.$bus.$emit('holidayDataUpdated', holidayMap);
      }
      
      return holidayMap;
    }
    return new Map();
  } catch (error) {
    return new Map();
  }
}

// 检查日期是否为节假日
export function isHoliday(dateStr) {
  if (holidayMap.has(dateStr)) {
    return holidayMap.get(dateStr).type === 2;
  }
  return false;
}

// 检查日期是否为工作日
export function isWorkday(dateStr) {
  if (holidayMap.has(dateStr)) {
    return holidayMap.get(dateStr).type === 1;
  }
  const date = dayjs(dateStr);
  const day = date.day();
  return day !== 0 && day !== 6;
}

// 请求房间列表
async function fetchRoomList(token) {
  try {
    const response = await axios.get('http://10.77.162.117:18092/admin/tjs/room/index', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.data && response.data.code === 200 && response.data.data && response.data.data.data) {
      const roomList = response.data.data.data;
      
      if (Array.isArray(roomList) && roomList.length > 0) {
        const roomNames = roomList.map(room => {
          if (room.name && room.name.trim() !== '') {
            return room.name;
          } else {
            return `房间${room.id}`;
          }
        });
        
        const roomIds = roomList.map(room => room.id || "");
        
        if (roomNames.length > 0) {
          nameList.length = 0;
          roomNames.forEach(name => nameList.push(name));
          
          roomIdList.length = 0;
          roomIds.forEach(id => roomIdList.push(id));
          
          dataReady = true;
          
          if (typeof dataUpdatedCallback === 'function') {
            dataUpdatedCallback(nameList);
          }
          
          window.dispatchEvent(new CustomEvent('roomListUpdated', { detail: nameList }));
          
          window._cachedData = null;
          
          if (window.$bus && nameList.length > 0) {
            const data = await fetchSchedulingData();
            if (data && data.length > 0) {
              window.$bus.$emit('dataGenerated', data);
            }
          }
        }
      }
    }
  } catch (error) {
    // 错误处理
  }
}

// 获取调度数据
export async function fetchSchedulingData() {
  try {
    const token = getAuthToken();
    if (!token || !roomIdList.length) {
      return [];
    }

    const datas = [];
    for (let i = 0; i < roomIdList.length; i++) {
      const roomId = roomIdList[i];
      const response = await axios.get('http://10.77.162.117:18092/admin/tjsScheduling/schedulingPlan/list', {
        params: { room: roomId },
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.data?.data?.data) {
        const tasks = response.data.data.data;
        datas.push({
          rawIndex: i,
          name: nameList[i],
          id: roomId,
          colorPair: {
            dark: "rgb(247, 167, 71,0.8)",
            light: "rgb(247, 167, 71,0.1)"
          },
          gtArray: tasks.map(task => ({
            id: task.order_num,
            passenger: task.userRealName,
            start: dayjs(new Date(task.start_time).toUTCString()).toString(),
            end: dayjs(new Date(task.end_time).toUTCString()).toString(),
            parentId: roomId,
            recordId: task.id // 保存预约记录的真实ID
          })).filter(task => dayjs(task.start).isValid() && dayjs(task.end).isValid())
        });
      }
    }
    return datas;
  } catch (error) {
    return [];
  }
}
